package com.stylefeng.guns.crawlers.zgzc;

import cn.wanghaomiao.seimi.annotation.Crawler;
import cn.wanghaomiao.seimi.struct.Request;
import cn.wanghaomiao.seimi.struct.Response;
import com.stylefeng.guns.common.persistence.model.Game;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.nodes.Element;
import org.seimicrawler.xpath.JXDocument;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

/**
 * 北单数据爬虫
 *
 * @author wuchong
 */
@Slf4j
@Getter
@Crawler(name = "bdCrawler")
public class BdCrawler extends BaseZgcpCrawler {

    private static final long serialVersionUID = -7040860604157677926L;

    /**
     * @return 设置起始url
     */
    @Override
    public String[] startUrls() {
        return new String[]{ZGZCW + "lottery/bdplayvsforJsp.action?lotteryId=200&v=1224"};
    }

    /**
     * 针对startUrl生成首批的response回调这个初始接口
     *
     * @param response --
     */
    @Override
    public void start(Response response) {

        JXDocument jxDocument = response.document();
        // 对阵列表
        List<Object> matchTrs = jxDocument.sel("//table[@class='mb']/tbody/tr");
        List<String> cacheMids = getMids();
//        cacheMids = Arrays.asList("2353582");
        for (Object object : matchTrs) {
            Element element = (Element) object;
            // 将tr数据转换为北单比赛内容
            String mid = element.getElementsByClass("wh-10 b-l").get(0).attr("newplayid");
            if (cacheMids.contains(mid)) {
                log.info("比赛{}已经存在", mid);
                continue;
            }
            String title = element.attr("m");
            String expire = element.attr("expire");
            if (isLeague(title) && "1".equals(expire)) {
                String zhud = element.getElementsByClass("wh-4 t-r").get(0).attr("tn");
                String ked = element.getElementsByClass("wh-6 t-l").get(0).attr("tn");
                //实际比分
                String actualScore = element.getElementsByClass("wh-5 bf").get(0).text();
                Game game = Game.builder().mid(mid).zhud(zhud).ked(ked).title(title)
                        .expire(expire).actualScore(actualScore).build();
                // 分析数据
                parseAnalysis(game);

            } else {
                log.warn("该场比赛={}不是联赛", mid);
            }

        }
    }

    @Scheduled(cron = "0 0 */2 * * ?")
    public void callByCron() {
        logger.info("我是一个根据cron表达式执行的调度器，2小时一次");
        // 可定时发送一个Request
        push(Request.build(startUrls()[0], "start").setSkipDuplicateFilter(true));
    }
}
